<template>
  <div class="modify-dialog">
    <slot></slot>
    <el-dialog
      width="40%"
      :close-on-click-modal="false"
      v-bind="dialogOpts"
      :visible.sync="dialogVisible"
    >
      <Form v-bind="formOpts" v-on="formEvent">
        <template #formSuf>
          <div style="margin-bottom: 20px">
            <el-row
              style="display: flex; align-items: center; margin-bottom: 15px"
            >
              <el-col :span="12">
                <div
                  style="width: 50px; white-space: nowrap; margin-bottom: 5px"
                >
                  退款方式：
                </div>
                <el-select
                  clearable
                  v-model="formData.payType"
                  size="small"
                  style="width: 200px"
                  placeholder="请选择退款方式"
                >
                  <el-option
                    v-for="item in refundList"
                    :key="item.payType"
                    :label="item.refundName"
                    :value="item.payType"
                  />
                </el-select>
              </el-col>
              <el-col :span="12">
                <div
                  style="width: 50px; white-space: nowrap; margin-bottom: 5px"
                >
                  退款金额：
                </div>
                <el-input-number
                  v-model="formData.refundAmount"
                  :min="0"
                  size="small"
                  style="width: 200px"
                  @change="changeNum('fourVisit', $event)"
                ></el-input-number>
              </el-col>
            </el-row>

            <el-row
              style="display: flex; align-items: center"
              v-if="formData.payType == 2"
            >
              <el-col :span="12">
                <div style="width: 50px; white-space: nowrap">银行卡卡号:</div>
                <el-input
                  size="small"
                  style="width: 280px"
                  v-model="formData.bankCard"
                ></el-input>
              </el-col>
              <el-col :span="12">
                <div style="width: 50px; white-space: nowrap">持卡人姓名:</div>
                <el-input
                  size="small"
                  style="width: 280px"
                  v-model="formData.cardHolderName"
                ></el-input>
              </el-col>
            </el-row>
            <el-row style="display: flex; align-items: center; margin: 15px 0">
              <el-col>
                <div style="white-space: nowrap; margin-bottom: 5px">
                  表格截图：
                </div>
                <el-upload
                  multiple
                  class="uploader-wrap"
                  :headers="headers"
                  :action="`${$apiHost}/common/fileImgUrl`"
                  :on-success="paySuc"
                  :show-file-list="false"
                >
                  <el-button size="small" type="primary">点击上传</el-button>
                  <div slot="tip" class="el-upload__tip">
                    只能上传jpg/png文件，且不超过500kb
                  </div>
                  <template #tip>
                    <div style="display: flex; width: 300px; flex-wrap: wrap">
                      <div
                        v-for="(item, index) in tableScreenshotList"
                        :key="index"
                        style="
                          display: flex;
                          align-items: flex-end;
                          width: 90px;
                          justify-content: space-between;
                        "
                      >
                        <el-image
                          :key="index"
                          :src="host + item"
                          :preview-src-list="
                            tableScreenshotList.map((img) => host + img)
                          "
                          style="width: 60px; height: 60px"
                          fit="cover"
                        >
                        </el-image>
                        <div @click="deletePic(index)">
                          <el-icon name="delete"></el-icon>
                        </div>
                      </div>
                    </div>
                  </template>
                </el-upload>
              </el-col>
              <el-col>
                <div style="margin-bottom: 5px; white-space: nowrap">
                  财务付款凭证：
                </div>
                <div>
                  <span style="color: gray; font-size: 12px"
                    >(粘贴复制即可上传图片)</span
                  >
                  <div class="div" style="display: flex; align-items: center">
                    <div
                      v-for="(v, i) in payImgList"
                      style="
                        display: flex;
                        align-items: center;
                        margin-right: 10px;
                      "
                      :key="i"
                    >
                      <el-image
                        v-if="v"
                        :key="i"
                        style="width: 50px; height: 50px"
                        ref="preview"
                        :src="host + v"
                        :preview-src-list="[host + v]"
                      >
                      </el-image>
                      <div @click="deleteImgVouchers(i)">
                        <el-icon name="delete"></el-icon>
                      </div>
                    </div>
                  </div>
                </div>
              </el-col>
            </el-row>
            <el-row
              style="display: flex; align-items: center; margin-top: 15px"
            >
              <el-col :span="12">
                <div
                  style="width: 88px; white-space: nowrap; margin-bottom: 5px"
                >
                  套件明细表格：
                </div>
                <el-upload
                  multiple
                  class="uploader-wrap"
                  :headers="headers"
                  :action="`${$apiHost}/common/fileImgUrl`"
                  :on-success="uploadSuccess"
                  :file-list="fileList"
                >
                  <el-button size="small" type="primary">点击上传</el-button>
                </el-upload>
              </el-col>
              <el-col :span="12" v-if="formData.payType == 1">
                <div style="white-space: nowrap; margin-bottom: 5px">
                  二维码截图：
                </div>
                <el-upload
                  multiple
                  class="uploader-wrap"
                  :headers="headers"
                  :action="`${$apiHost}/common/fileImgUrl`"
                  :on-success="qrcodeSuc"
                  :show-file-list="false"
                >
                  <el-button size="small" type="primary">点击上传</el-button>
                  <div slot="tip" class="el-upload__tip">
                    只能上传jpg/png文件，且不超过500kb
                  </div>
                  <template #tip>
                    <div style="display: flex; width: 300px; flex-wrap: wrap">
                      <div
                        v-for="(item, index) in qrcodeList"
                        :key="index"
                        style="
                          display: flex;
                          align-items: flex-end;
                          width: 90px;
                          justify-content: space-between;
                        "
                      >
                        <el-image
                          style="width: 60px; height: 60px"
                          :key="index"
                          :src="host + item"
                          :preview-src-list="
                            qrcodeList.map((img) => host + img)
                          "
                          class="img-item"
                          fit="cover"
                        >
                        </el-image>
                        <div @click="deletePic(index)">
                          <el-icon name="delete"></el-icon>
                        </div>
                      </div>
                    </div>
                  </template>
                </el-upload>
              </el-col>
            </el-row>
            <el-row style="margin-top: 15px">
              <el-col :span="12">
                <div style="white-space: nowrap; margin-bottom: 5px">
                  备注：
                </div>
                <el-input
                  type="textarea"
                  :rows="4"
                  placeholder="请输入内容"
                  v-model="formData.refundReason"
                  style="width: 300px"
                >
                </el-input>
              </el-col>
              <!-- <el-col style="display: flex; align-items: center" :span="12">
                <el-button type="primary" @click="lookDetail"
                  >查看退款详情</el-button
                >
              </el-col> -->
            </el-row>
          </div>
        </template>
        <template #formBtn>
          <div class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="onConfirm" v-prevent-re-click>
              确 定</el-button
            >
          </div>
        </template>
      </Form>
    </el-dialog>
    <el-dialog
      :visible.sync="showDetail"
      :title="detailTitle"
      top="10px"
      width="70%"
    >
      <!-- payType: 1, // 退款方式 excel: null, // 文件流对象 excelPath: '', //
      文件流上传路径 refundAmount: 0, // 退款金额 refundReason: '', //
      备注退款原因 bankCard: '', // 输入银行卡号 cardHolderName: '', //
      持卡人姓名 qrcode: '', // 二维码 payVoucherStr: '', // 付款凭证截图
      tableScreenshotStr: '', // 表格凭证截图 -->

      <el-table :data="detailList" style="width: 100%">
        <el-table-column
          v-for="col in columns"
          :key="col.prop"
          :prop="col.prop"
          :label="col.label"
        >
          <template v-slot:default="scope">
            <div v-if="col.prop === 'qrCode'">
              <div style="display: flex">
                <div v-if="!scope.row.qrCode.length">无二维码截图</div>
                <div v-else>
                  <el-image
                    v-for="(item, index) in scope.row.qrCode"
                    :key="index"
                    :src="host + item"
                    style="width: 60px; height: 60px"
                    :preview-src-list="
                      scope.row.qrCode.map((img) => host + img)
                    "
                    class="img-item"
                    fit="cover"
                  >
                  </el-image>
                </div>
              </div>
            </div>
            <div v-else-if="col.prop === 'payVoucherStr'">
              <div style="display: flex">
                <div v-if="!scope.row.payVoucherStr.length">无付款凭证截图</div>
                <div v-else>
                  <el-image
                    v-for="(item, index) in scope.row.payVoucher"
                    :key="index"
                    :src="host + item"
                    style="width: 60px"
                    :preview-src-list="
                      scope.row.payVoucher.map((img) => host + img)
                    "
                    class="img-item"
                    fit="cover"
                  >
                  </el-image>
                </div>
              </div>
            </div>
            <div v-else-if="col.prop === 'tableScreenshotStr'">
              <div style="display: flex">
                <el-image
                  v-for="(item, index) in scope.row.tableScreenshot"
                  :key="index"
                  :src="host + item"
                  style="width: 60px"
                  :preview-src-list="
                    scope.row.tableScreenshot.map((img) => host + img)
                  "
                  class="img-item"
                  fit="cover"
                >
                </el-image>
              </div>
            </div>
            <div v-else-if="col.prop === 'excel'">
              <div style="display: flex">
                <el-link
                  style="color: aqua; text-decoration: underline"
                  @click="inToUrl(scope.row.excelPath)"
                  >{{ scope.row.excel }}</el-link
                >
              </div>
            </div>

            <p v-else @click="cellClick(scope.row, col.prop)">
              {{ scope.row[col.prop] }}
            </p>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import modifyMixins from '@/mixins/modifyMixins.vue'
import axios from 'axios'
import store from '../../../store'

export default {
  name: 'modifyRefund',
  mixins: [modifyMixins],
  data() {
    return {
      formData: {
        orderId: 0,
        payType: '', // 退款方式
        excel: null, // 文件流对象
        excelPath: '', // 文件流上传路径
        refundAmount: 0, // 退款金额
        refundReason: '', // 备注退款原因
        bankCard: '', // 输入银行卡号
        cardHolderName: '', // 持卡人姓名
        qrCode: [], // 二维码
        payVoucherStr: '', // 付款凭证截图
        tableScreenshotStr: '', // 表格凭证截图
      },
      dialogTitle: '退款',
      row: {},
      host: this.$imgHost,
      isShow: false,
      showDetail: false,
      tableScreenshotList: [], // 表格截图
      payImgList: [], // 财务付款凭证
      qrcodeList: [],
      detailTitle: '退款明细',
      fileList: [], // 表格截图回显
      fileList1: [], // 二维码截图回显
      refundList: [
        {
          payType: 1,
          refundName: '微信/支付宝二维码',
        },
        {
          payType: 2,
          refundName: '银行卡支付',
        },
      ],
      textarea: '',
      detailList: [], // 退款明细表格
      columns: [
        { prop: 'orderId', label: '订单ID' },
        { prop: 'payType', label: '退款方式' },
        { prop: 'refundAmount', label: '退款金额' },
        { prop: 'excel', label: '套件明细Excel' },
        { prop: 'bankCard', label: '银行卡号' },
        { prop: 'cardHolderName', label: '持卡人姓名' },
        { prop: 'qrCode', label: '二维码截图' },
        { prop: 'payVoucherStr', label: '付款凭证截图' },
        { prop: 'tableScreenshotStr', label: '表格截图' },
        { prop: 'refundReason', label: '备注' },
      ],
      tableScreenshot: [], // 表格图片预览
      payVoucher: [], // 凭证预览
      qrCode: [], // 二维码预览
    }
  },
  created() {
    // document.addEventListener('paste', this.handlePaste)
  },
  computed: {
    headers() {
      const token = this.$quinn.getStorage('token')
      return {
        token,
      }
    },
  },
  methods: {
    async onConfirm() {
      const {
        // orderId,
        payType,
        excel,
        excelPath,
        refundAmount,
        refundReason,
        bankCard,
        cardHolderName,
        qrCode,
        payVoucherStr,
        tableScreenshotStr,
      } = this.formData
      console.log('payType', payType)
      // if (!orderId) return this.$message.error('无订单ID!')
      if (!payType) return this.$message.error('请选择退款方式!')
      if (!excel && !excelPath) return this.$message.error('请选择上传文件!')
      if (!refundAmount) return this.$message.error('请选择退款金额!')
      if (payType == 2) {
        if (!bankCard) return this.$message.error('请选择退款账号!')
        if (!cardHolderName) return this.$message.error('请选择执卡人姓名!')
      } else if (payType == 1) {
        if (!qrCode) return this.$message.error('请上传退款二维码!')
      }
      if (!payVoucherStr) return this.$message.error('请上传付款凭证!')
      if (!tableScreenshotStr) return this.$message.error('请上传表格截图!')
      const formData = new FormData()
      formData.append('orderId', this.row.id)
      formData.append('payType', payType)
      formData.append('excel', excel)
      formData.append('excelPath', excelPath)
      formData.append('refundAmount', refundAmount)
      formData.append('refundReason', refundReason)
      formData.append('bankCard', bankCard)
      formData.append('cardHolderName', cardHolderName)
      formData.append('qrCode', qrCode)
      formData.append('payVoucherStr', payVoucherStr)
      formData.append('tableScreenshotStr', tableScreenshotStr)
      const res = await this.$api.refundAddCustomerRefund(formData)
      if (res == 1) {
        this.$message.success('退款成功!')
        this.dialogVisible = false
      }
    },
    onSubmit(form) {
      const { modify, row, fileList } = this
      console.log(row)
    },
    inToUrl(el) {
      window.open('https:' + el)
    },
    async lookDetail(orderId) {
      this.showDetail = true
      if (this.showDetail) {
        const data = { orderId: 104819 }
        const res = await this.$api.refundGetCustomerRefund(data)
        if (res.length) {
          const qrCodeList = []
          res.forEach((el) => {
            if (el.qrCode) {
              qrCodeList.push(el.qrCode)
              el.qrCode = qrCodeList
              console.log('el.qrCode', el.qrCode)
            } else {
              el.qrCode = []
            }

            if (el.payType == 1) {
              el.payType = '微信/支付宝二维码'
            } else if (el.payType == 2) {
              el.payType = '银行卡支付'
            }
            // 表格处理
            if (el.excelPath) {
              // console.log('el.excelPath', el.excelPath)
              const arrTemp = el.excelPath.split('/')
              el.excel = arrTemp[3].substring(14) // 表格名称
              // console.log('el.excelName', el.excel)
            }
          })
          this.detailList = res
          console.log('this.detailList', res)
        }

        // this.tableScreenshot = res[0].tableScreenshot
        // this.payVoucher = res[0].payVoucher
        // this.qrCode = res[0].qrCode || []
      }
    },
    changeNum(field, val) {
      if (!val) {
        this.$set(this.data, field, 0)
      }
    },
    /**
     * 方法说明
     * author: iceyhu
     * description: 表格上传
     * @param
     * @return
     * @createTime: DATE_TIME
     */
    uploadSuccess(response, file, fileList) {
      // response, file, fileList
      // console.log('response', response)
      // console.log('file', file)
      // console.log('fileList', fileList)
      if (response.code == 200 && response.result) {
        this.fileList = fileList
        this.formData.excelPath = response.result[0] // 文件流上传路径
        this.formData.excel = file.raw // 文件流对象
      }
    },
    qrcodeUpload(response, file, fileList) {
      // response, file, fileList
      // console.log('response', response)
      // console.log('file', file)
      // console.log('fileList', fileList)
      if (response.code == 200 && response.result) {
        this.fileList = fileList
        this.formData.excelPath = response.result[0] // 文件流上传路径
        this.formData.excel = file.raw // 文件流对象
      }
    },
    /**
     * 方法说明
     * author: iceyhu
     * description: 关闭弹窗
     * @param
     * @return
     * @createTime: DATE_TIME
     */
    handleCancel() {
      this.isShow = false
    },
    handlePreview(file) {
      console.log(file)
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      )
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    preview() {
      const { id } = this.row
      let url = `${LOGIN_PATH}#/quoteExport?type=preview&id=${id}&token=${this.token}`
      window.open(url, '_blank', 'height=667 ,width=375,top=200,left=400')
    },
    handlePaste(event) {
      // if (!this.dialogAdd) return
      const clipboardData = event.clipboardData
      console.log('clipboardData', clipboardData)
      if (clipboardData) {
        for (let i = 0; i < clipboardData.items.length; i++) {
          const item = clipboardData.items[i]
          if (item.kind === 'file' && item.type.startsWith('image/')) {
            const file = item.getAsFile()
            if (file) {
              this.uploadImage(file) // 处理文件上传逻辑
            }
          } else {
            this.$message.error('请拷贝图片8!')
            break
          }
        }
      }
    },
    uploadImage(imageFile) {
      console.log('imageFile', imageFile)

      const formData = new FormData()
      formData.append('file', imageFile)
      axios
        .post(`${this.$apiHost}/common/fileImgUrl`, formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
            token: window.$quinn.getStorage('token'),
          },
        })
        .then((response) => {
          this.payImgList.push(response.data.result[0])
          // console.log('this.payImgList', this.payImgList)
          this.formData.payVoucherStr = this.payImgList.join(',')
        })
        .catch((error) => {})
    },
    showDialog(modify = 'detail', row = {}) {
      this.dialogVisible = true
      this.row = row
      this.modify = modify || 'detail'
    },
    deletePic(i) {
      this.tableScreenshotList.splice(i, 1)
      this.qrcodeList.splice(i, 1)
    },
    deleteImgVouchers(i) {
      this.payImgList.splice(i, 1)
    },
    /**
     * 方法说明
     * author: iceyhu
     * description: 处理文件地址为字符串
     * @param
     * @return
     * @createTime: DATE_TIME
     */
    paySuc(res) {
      if (res.code == 200 && res.result) {
        this.tableScreenshotList.push(res.result[0])
        this.formData.tableScreenshotStr = this.tableScreenshotList.join(',')
        console.log('res.result[0]', res.result[0])
      }
    },
    /**
     * 方法说明
     * author: iceyhu
     * description: 二维码截图
     * @param
     * @return
     * @createTime: DATE_TIME
     */
    qrcodeSuc(res) {
      if (res.code == 200 && res.result) {
        this.qrcodeList.push(res.result[0])
        this.formData.qrCode = this.qrcodeList.join(',')
        console.log('this.formData.qrcode ', this.formData.qrCode)
      }
    },
  },
}
</script>
<style lang="less" scoped>
.detail-wrap {
  max-height: 70vh;
  overflow-y: auto;
  .title {
    font-size: 18px;
    font-weight: bold;
    color: #333;
    margin-bottom: 12px;
  }
  .item {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
    &.align-start {
      align-items: flex-start;
    }
    .label {
      font-size: 14px;
      font-weight: bold;
      color: #666;
      width: 90px;
      text-align: right;
    }
    .value {
      flex: 1;
      overflow: hidden;
      word-break: break-all;
      white-space: pre-wrap;
    }
  }
  .total-wrap {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    padding-right: 20px;
    .p1 {
      padding-right: 25px;
    }
  }
  .quote-item {
    padding-left: 20px;
    margin-bottom: 20px;
    .quote-title {
      font-size: 14px;
      font-weight: bold;
      color: #666;
      position: relative;
      @size: 8px;
      &::before {
        display: inline-block;
        content: '';
        position: absolute;
        width: @size;
        height: @size;
        background: #409eff;
        border-radius: 50%;
        left: -15px;
        top: 50%;
        margin-top: -4px;
      }
    }
    .quote {
      padding-left: 20px;
      display: flex;
      margin-top: 15px;
      .info {
        flex: 1;
        overflow: hidden;
        padding-left: 15px;
        span {
          margin-right: 8px;
        }
        .price {
          margin-right: 20px;
          color: #e6a23c;
        }
        .infoname {
          font-weight: bold;
          color: #666;
        }
        .infotip {
          margin-top: 5px;
        }
      }
    }
  }
}
</style>
